{include file="common/header"}

<div class="container mx-auto px-4 py-6">
  <div class="max-w-4xl mx-auto">
    <h1 class="text-3xl font-bold text-center mb-8">主动报工</h1>
    
    {if condition="$error"}
    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
      {$error}
    </div>
    {/if}
    
    {if condition="$success"}
    <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
      {$success}
    </div>
    {/if}
    
    <form id="activeReportForm" method="post" enctype="multipart/form-data" class="bg-white shadow-lg rounded-lg p-6">
      <!-- 订单选择 -->
      <div class="mb-6">
        <label class="block text-gray-700 text-sm font-bold mb-2">选择订单</label>
        <select id="order-select" name="order_id" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" required>
          <option value="">请选择订单</option>
          {volist name="orders" id="order"}
          <option value="{$order.id}">{$order.order_no} - {$order.customer_name}</option>
          {/volist}
        </select>
      </div>
      
      <!-- 产品选择 -->
      <div class="mb-6">
        <label class="block text-gray-700 text-sm font-bold mb-2">选择产品</label>
        <select id="product-select" name="product_id" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" required>
          <option value="">请先选择订单</option>
        </select>
      </div>
      
      <!-- 型号和工序选择 -->
      <div class="mb-6">
        <label class="block text-gray-700 text-sm font-bold mb-2">选择型号和工序</label>
        <select id="model-process-select" name="model_process" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" required>
          <option value="">请先选择产品</option>
        </select>
      </div>
      
      <!-- 产品型号工序信息 -->
      <div id="model-process-info" class="mb-6 p-4 bg-gray-50 rounded-md" style="display: none;">
        <h3 class="font-bold text-lg mb-2">产品型号工序信息</h3>
        <div class="grid grid-cols-2 gap-4">
          <div>
            <span class="font-semibold">产品：</span>
            <span id="product-name"></span>
          </div>
          <div>
            <span class="font-semibold">型号：</span>
            <span id="model-name"></span>
          </div>
          <div>
            <span class="font-semibold">工序：</span>
            <span id="process-name"></span>
          </div>
          <div>
            <span class="font-semibold">订单数量：</span>
            <span id="order-quantity"></span>
          </div>
          <div>
            <span class="font-semibold">计件工价：</span>
            <span id="piece-price"></span>
          </div>
          <div>
            <span class="font-semibold">计时工价：</span>
            <span id="time-price"></span>
          </div>
        </div>
      </div>
      
      <!-- 生产数量 -->
      <div class="mb-6">
        <label class="block text-gray-700 text-sm font-bold mb-2">生产数量</label>
        <input type="number" id="quantity-input" name="quantity" min="1" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" required>
      </div>
      
      <!-- 工作日期 -->
      <div class="mb-6">
        <label class="block text-gray-700 text-sm font-bold mb-2">工作日期</label>
        <input type="date" id="work-date" name="work_date" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" required>
      </div>
      
      <!-- 工作时间 -->
      <div class="mb-6">
        <label class="block text-gray-700 text-sm font-bold mb-2">工作时间</label>
        <div class="grid grid-cols-2 gap-4">
          <div>
            <label class="block text-gray-600 text-sm mb-1">开始时间</label>
            <input type="time" id="start-time" name="start_time" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
          </div>
          <div>
            <label class="block text-gray-600 text-sm mb-1">结束时间</label>
            <input type="time" id="end-time" name="end_time" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
          </div>
        </div>
        <div id="time-calculator" class="mt-2 p-2 bg-blue-50 rounded" style="display: none;">
          <span class="text-sm text-blue-700">计算工作时长：<span id="calculated-hours">0</span> 小时</span>
        </div>
      </div>
      
      <!-- 工资计算 -->
      <div id="wage-calculator" class="mb-6 p-4 bg-yellow-50 rounded-md" style="display: none;">
        <h3 class="font-bold text-lg mb-2">工资计算</h3>
        <div class="grid grid-cols-3 gap-4">
          <div>
            <span class="font-semibold">计件工资：</span>
            <span id="calculated-piece-wage">0.00</span> 元
          </div>
          <div>
            <span class="font-semibold">计时工资：</span>
            <span id="calculated-time-wage">0.00</span> 元
          </div>
          <div>
            <span class="font-semibold">总工资：</span>
            <span id="calculated-total-wage">0.00</span> 元
          </div>
        </div>
      </div>
      
      <!-- 完工图片 -->
      <div class="mb-6">
        <label class="block text-gray-700 text-sm font-bold mb-2">完工图片（最多9张）</label>
        <div class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center">
          <input type="file" id="image-upload" name="images[]" multiple accept="image/*" class="hidden">
          <label for="image-upload" class="cursor-pointer">
            <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-2"></i>
            <p class="text-gray-600">点击选择图片或拖拽图片到此处</p>
          </label>
        </div>
        <div id="image-preview" class="mt-4 grid grid-cols-3 gap-2"></div>
      </div>
      
      <!-- 备注 -->
      <div class="mb-6">
        <label class="block text-gray-700 text-sm font-bold mb-2">备注</label>
        <textarea name="remark" rows="3" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="请输入备注信息"></textarea>
      </div>
      
      <!-- 提交按钮 -->
      <div class="flex gap-4">
        <button type="submit" class="flex-1 bg-blue-600 text-white py-3 px-6 rounded-md font-bold hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500">
          <i class="fas fa-save mr-2"></i>提交报工
        </button>
        <a href="{:url('index/active_report/records')}" class="flex-1 bg-gray-500 text-white py-3 px-6 rounded-md font-bold hover:bg-gray-600 text-center">
          <i class="fas fa-list mr-2"></i>我的记录
        </a>
      </div>
    </form>
  </div>
</div>

<script>
$(document).ready(function() {
    // 设置默认日期为今天
    $('#work-date').val(new Date().toISOString().split('T')[0]);
    
    // 订单选择变化事件
    $('#order-select').on('change', function() {
        var orderId = $(this).val();
        if (orderId) {
            loadOrderProducts(orderId);
        } else {
            $('#product-select').html('<option value="">请先选择订单</option>');
            $('#model-process-select').html('<option value="">请先选择产品</option>');
            $('#model-process-info').hide();
        }
    });
    
    // 产品选择变化事件
    $('#product-select').on('change', function() {
        var productId = $(this).val();
        var orderId = $('#order-select').val();
        if (productId && orderId) {
            loadProductModels(orderId, productId);
        } else {
            $('#model-process-select').html('<option value="">请先选择产品</option>');
            $('#model-process-info').hide();
        }
    });
    
    // 型号和工序选择变化事件
    $('#model-process-select').on('change', function() {
        var selectedValue = $(this).val();
        if (selectedValue) {
            var selectedOption = $(this).find('option:selected');
            var piecePrice = parseFloat(selectedOption.data('piece-price'));
            var timePrice = parseFloat(selectedOption.data('time-price'));
            var orderQuantity = parseInt(selectedOption.data('order-quantity'));
            var modelName = selectedOption.data('model-name');
            var processName = selectedOption.data('process-name');
            var productName = selectedOption.data('product-name');
            
            // 显示信息
            $('#product-name').text(productName);
            $('#model-name').text(modelName);
            $('#process-name').text(processName);
            $('#order-quantity').text(orderQuantity);
            $('#piece-price').text(piecePrice.toFixed(2) + ' 元/件');
            $('#time-price').text(timePrice.toFixed(2) + ' 元/小时');
            $('#model-process-info').show();
            
            // 更新最大可报工数量
            $('#quantity-input').attr('max', orderQuantity);
            
            calculateWage();
        } else {
            $('#model-process-info').hide();
        }
    });
    
    // 数量和时间变化事件
    $('#quantity-input, #start-time, #end-time').on('input change', function() {
        calculateWage();
    });
    
    // 图片上传预览
    $('#image-upload').on('change', function() {
        console.log('=== 图片上传调试 ===');
        var files = this.files;
        console.log('选择的文件数量:', files.length);
        
        var preview = $('#image-preview');
        preview.empty();
        
        for (var i = 0; i < files.length && i < 9; i++) {
            var file = files[i];
            console.log('文件' + i + ':', {
                name: file.name,
                size: file.size,
                type: file.type
            });
            
            if (file.type.startsWith('image/')) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    preview.append('<img src="' + e.target.result + '" class="w-full h-24 object-cover rounded">');
                };
                reader.readAsDataURL(file);
            } else {
                console.log('文件' + i + '不是图片格式');
            }
        }
    });
    
    // 表单提交
    $('#activeReportForm').on('submit', function(e) {
        e.preventDefault();
        submitActiveReport();
    });
});

// 加载订单下的产品
function loadOrderProducts(orderId) {
    $.ajax({
        url: '/index/active_report/getOrderProducts',
        method: 'GET',
        data: { order_id: orderId },
        success: function(response) {
            if (response.code === 1) {
                var options = '<option value="">请选择产品</option>';
                response.data.forEach(function(product) {
                    options += '<option value="' + product.product_id + '">' + product.product_name + '</option>';
                });
                $('#product-select').html(options);
            } else {
                alert(response.msg || '加载产品失败');
            }
        },
        error: function() {
            alert('网络错误，请重试');
        }
    });
}

// 加载产品下的型号和工序
function loadProductModels(orderId, productId) {
    $.ajax({
        url: '/index/active_report/getProductModels',
        method: 'GET',
        data: { 
            order_id: orderId,
            product_id: productId
        },
        success: function(response) {
            if (response.code === 1) {
                var options = '<option value="">请选择型号和工序</option>';
                response.data.forEach(function(item) {
                    var displayText = item.display_name + ' - 订单数量:' + item.order_quantity;
                    options += '<option value="' + item.model_id + ':' + item.process_id + '" ' +
                              'data-piece-price="' + item.piece_price + '" ' +
                              'data-time-price="' + item.time_price + '" ' +
                              'data-order-quantity="' + item.order_quantity + '" ' +
                              'data-model-name="' + item.model_name + '" ' +
                              'data-process-name="' + item.process_name + '" ' +
                              'data-product-name="' + $('#product-select option:selected').text() + '">' + displayText + '</option>';
                });
                $('#model-process-select').html(options);
            } else {
                alert(response.msg || '加载型号和工序失败');
            }
        },
        error: function() {
            alert('网络错误，请重试');
        }
    });
}



// 计算工作时长
function calculateWorkHours() {
    var startTime = $('#start-time').val();
    var endTime = $('#end-time').val();
    
    if (startTime && endTime) {
        var start = new Date('2000-01-01 ' + startTime);
        var end = new Date('2000-01-01 ' + endTime);
        
        if (end > start) {
            var diffHours = (end - start) / (1000 * 60 * 60);
            $('#calculated-hours').text(diffHours.toFixed(2));
            $('#time-calculator').show();
            return diffHours;
        } else {
            $('#time-calculator').hide();
            alert('结束时间必须晚于开始时间');
            return 0;
        }
    } else {
        $('#time-calculator').hide();
        return 0;
    }
}

// 计算工资
function calculateWage() {
    var quantity = parseInt($('#quantity-input').val()) || 0;
    var workHours = calculateWorkHours();
    var piecePrice = parseFloat($('#piece-price').text()) || 0;
    var timePrice = parseFloat($('#time-price').text()) || 0;
    
    var pieceWage = quantity * piecePrice;
    var timeWage = workHours * timePrice;
    var totalWage = pieceWage + timeWage;
    
    $('#calculated-piece-wage').text(pieceWage.toFixed(2));
    $('#calculated-time-wage').text(timeWage.toFixed(2));
    $('#calculated-total-wage').text(totalWage.toFixed(2));
    
    if (quantity > 0 || workHours > 0) {
        $('#wage-calculator').show();
    } else {
        $('#wage-calculator').hide();
    }
}

// 提交主动报工
function submitActiveReport() {
    console.log('=== 表单提交调试 ===');
    
    var formData = new FormData($('#activeReportForm')[0]);
    var btn = $('#activeReportForm button[type=submit]');
    var originalText = btn.html();
    
    // 调试：显示表单数据
    console.log('表单数据:');
    for (var pair of formData.entries()) {
        console.log(pair[0] + ': ' + pair[1]);
    }
    
    // 调试：显示文件信息
    var files = $('#image-upload')[0].files;
    console.log('上传文件数量:', files.length);
    for (var i = 0; i < files.length; i++) {
        console.log('文件' + i + ':', files[i].name, '大小:', files[i].size);
    }
    
    btn.html('<i class="fa fa-spinner fa-spin mr-2"></i>提交中...').prop('disabled', true);
    
    console.log('开始发送AJAX请求...');
    
    $.ajax({
        url: window.location.href,
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            console.log('服务器响应:', response);
            if (response.code === 1) {
                alert('报工提交成功！');
                setTimeout(function() {
                    window.location.href = '/index/active_report/records';
                }, 1500);
            } else {
                alert(response.msg || '提交失败');
                btn.html(originalText).prop('disabled', false);
            }
        },
        error: function(xhr, status, error) {
            console.log('AJAX错误:', xhr, status, error);
            console.log('响应文本:', xhr.responseText);
            alert('网络错误，请重试');
            btn.html(originalText).prop('disabled', false);
        }
    });
}
</script>

{include file="common/footer"} 